<template>
  <div class="index-container">
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <div class="nav-title">健康食品推荐系统</div>
      <div
        class="user-info"
        @click="
          isLoggedIn ? (showUserActionSheet = true) : navigateTo('/login')
        "
      >
        <van-icon name="manager-o" size="16" />
        <span class="user-name">{{
          isLoggedIn ? userInfo.nickname || userInfo.username || "用户" : "登录"
        }}</span>
        <van-icon v-if="isLoggedIn" name="arrow-down" size="12" />
      </div>
    </div>
    <div class="nav-placeholder"></div>

    <!-- 用户操作面板 -->
    <van-action-sheet
      v-model="showUserActionSheet"
      :actions="userActions"
      cancel-text="取消"
      close-on-click-action
      @select="handleUserAction"
    />

    <!-- 轮播图部分 -->
    <div class="banner-section">
      <van-swipe :autoplay="3000" indicator-color="#1989fa">
        <van-swipe-item v-for="(banner, index) in banners" :key="index">
          <div class="banner-image-container">
            <van-image
              width="100%"
              height="100%"
              fit="cover"
              :src="banner.image"
              alt="banner"
            />
          </div>
          <div class="banner-title">{{ banner.title }}</div>
        </van-swipe-item>
      </van-swipe>
    </div>

    <!-- 功能导航网格 -->
    <div class="function-grid">
      <div class="function-item" @click="navigateTo('/recipe/search')">
        <div class="function-item-icon">
          <van-icon name="search" size="24" color="#1989fa" />
        </div>
        <div class="function-item-text">搜索食谱</div>
      </div>
      <div class="function-item" @click="navigateTo('/food/analysis')">
        <div class="function-item-icon">
          <van-icon name="bar-chart-o" size="24" color="#ff976a" />
        </div>
        <div class="function-item-text">食品分析</div>
      </div>
      <div class="function-item" @click="navigateTo('/recommendation')">
        <div class="function-item-icon">
          <van-icon name="fire-o" size="24" color="#ee0a24" />
        </div>
        <div class="function-item-text">最新推荐</div>
      </div>
      <div class="function-item" @click="navigateTo('/user')">
        <div class="function-item-icon">
          <van-icon name="manager-o" size="24" color="#07c160" />
        </div>
        <div class="function-item-text">个人中心</div>
      </div>
    </div>

    <!-- 推荐食谱部分 -->
    <div class="section-title">
      <span>推荐食谱</span>
      <span class="more" @click="navigateTo('/recipe/list')">查看更多</span>
    </div>

    <div class="recipe-list">
      <div
        v-for="recipe in recommendedRecipes"
        :key="recipe.id"
        class="recipe-card"
        @click="navigateTo(`/recipe/${recipe.id}`)"
      >
        <div class="recipe-image-container">
          <img
            width="100%"
            height="100%"
            :src="recipe.imageUrl"
            fit="cover"
            referrerpolicy="no-referrer"
          />
        </div>
        <div class="recipe-card-content">
          <div class="recipe-card-title">{{ recipe.name }}</div>
          <div class="recipe-card-desc">{{ recipe.desc }}</div>
        </div>
      </div>
    </div>

    <!-- 健康食品部分 -->
    <div class="section-title">
      <span>热门食品</span>
      <span class="more" @click="navigateTo('/food/list')">查看更多</span>
    </div>

    <div class="food-list">
      <div
        v-for="food in hotRecipes"
        :key="food.id"
        class="food-card"
        @click="navigateTo(`/food/${food.id}`)"
      >
        <img
          width="100%"
          height="70"
          :src="food.imageUrl"
          fit="cover"
          referrerpolicy="no-referrer"
        />
        <div class="food-card-title">{{ food.name }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/userStore";
import { showToast } from "vant";
import { getRecipeList, getRecommendedRecipeList } from "@/api/recipe";
import { getRecommendationList } from "@/api/recommendation";
const router = useRouter();
const userStore = useUserStore();

// 用户信息和登录状态
const userInfo = computed(() => userStore.userInfo);
const isLoggedIn = computed(() => userStore.isLoggedIn);

// 用户操作面板
const showUserActionSheet = ref(false);
const userActions = [
  { name: "个人中心", icon: "manager-o" },
  { name: "我的收藏", icon: "star-o" },
  { name: "退出登录", icon: "revoke", className: "logout-action" },
];

// 处理用户操作选择
const handleUserAction = (action) => {
  showUserActionSheet.value = false;
  if (action.name === "退出登录") {
    userStore.logout();
    showToast("已退出登录");
    router.push("/");
  } else if (action.name === "个人中心") {
    navigateTo("/user");
  } else if (action.name === "我的收藏") {
    navigateTo("/user/favorites");
  }
};

// 页面导航
const navigateTo = (path) => {
  router.push(path);
};

// 示例数据
const banners = ref([
  {
    image: new URL("@/assets/images/banner1.jpg", import.meta.url).href,
    title: "健康饮食每一天",
  },
  {
    image: new URL("@/assets/images/banner2.jpg", import.meta.url).href,
    title: "营养搭配更科学",
  },
  {
    image: new URL("@/assets/images/banner3.jpg", import.meta.url).href,
    title: "绿色",
  },
  {
    image: new URL("@/assets/images/banner4.jpg", import.meta.url).href,
    title: "健康",
  },
]);

const recommendedRecipes = ref([]);
const recQueryParams = ref({
  current: 1,
  size: 10,
});
const getRecommendedRecipes = () => {
  recQueryParams.value.userId = userInfo.value.id;
  getRecommendationList(recQueryParams.value)
    .then((res) => {
      if (res && res.data && res.data.records) {
        recommendedRecipes.value = res.data.records;
        // 为推荐食谱初始化加载状态
        initImageLoading(recommendedRecipes.value);
        console.log("推荐食谱数据:", recommendedRecipes.value);
      } else {
        recommendedRecipes.value = [];
        console.error("获取推荐食谱数据格式错误:", res);
      }
    })
    .catch((err) => {
      recommendedRecipes.value = [];
      console.error("获取推荐食谱失败:", err);
    });
};

const hotRecipes = ref([]);

// 添加图片错误处理函数

const queryParams = ref({
  current: Math.floor(Math.random() * 10) + 1, // 1-10 随机
  size: 8,
});
const getHotRecipes = () => {
  getRecipeList({ current: 1, size: 14 })
    .then((res) => {
      if (res && res.data && res.data.records) {
        hotRecipes.value = res.data.records;
        // 为热门食谱初始化加载状态
        initImageLoading(hotRecipes.value);
        console.log("热门食谱数据:", hotRecipes.value);
      } else {
        hotRecipes.value = [];
        console.error("获取热门食谱数据格式错误:", res);
      }
    })
    .catch((err) => {
      hotRecipes.value = [];
      console.error("获取热门食谱失败:", err);
    });
};

// 图片加载状态
const loadingImages = ref({});

// 初始化所有图片为加载中状态
const initImageLoading = (recipes) => {
  const loadingState = {};
  recipes.forEach((recipe) => {
    loadingState[recipe.id] = true;
  });
  loadingImages.value = loadingState;
};

// 图片加载完成
const imageLoaded = (id) => {
  loadingImages.value[id] = false;
};

// 页面加载时获取数据
onMounted(() => {
  getHotRecipes();
  getRecommendedRecipes();
});
</script>

<style scoped>
.index-container {
  padding: 16px;
  padding-bottom: 50px;
  background-color: #f8f8f8;
}

/* 优化导航栏 */
.top-nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 46px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  background-color: #fff;
  border-bottom: 1px solid #f5f5f5;
  z-index: 100;
}

.nav-placeholder {
  height: 46px;
}

.nav-title {
  font-size: 16px;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #666;
  padding: 5px 10px;
  border-radius: 16px;
  background-color: #f5f5f5;
  transition: background-color 0.3s;
}

.user-info:active {
  background-color: #e8e8e8;
}

.user-name {
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 用户操作菜单 */
.logout-action {
  color: #ee0a24;
}

/* 轮播图区域 */
.banner-section {
  margin: 16px auto;
  border-radius: 8px;
  overflow: hidden;
  width: 90%; /* 设置宽度为80%，原为90% */
}

.banner-image-container {
  width: 100%;
  height: 375px; /* 固定高度，对应图片原高度的一半，维持比例 */
  position: relative;
}

.banner-image-container .van-image {
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.banner-title {
  position: absolute;
  bottom: 10px; /* 减小距离底部的距离 */
  left: 20px;
  right: 20px;
  color: white;
  font-size: 16px; /* 减小字体大小 */
  font-weight: bold;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
  background-color: rgba(0, 0, 0, 0.4);
  padding: 6px 10px; /* 减小内边距 */
  border-radius: 4px;
  text-align: center;
}

/* 功能模块区域 */
.section-title {
  margin: 15px 0 10px;
  padding: 0 16px;
  font-size: 16px;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title .more {
  font-size: 13px;
  color: #999;
  font-weight: normal;
}

.function-grid {
  padding: 5px 10px 15px;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  text-align: center;
}

.function-item {
  padding: 10px 0;
}

.function-item-icon {
  width: 44px;
  height: 44px;
  margin: 0 auto 5px;
  background-color: #f5f7fa;
  border-radius: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.function-item-text {
  font-size: 12px;
  color: #323233;
}

/* 食谱卡片区域 */
.recipe-list,
.food-list {
  padding: 0 16px;
  overflow-x: auto;
  display: flex;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.recipe-list::-webkit-scrollbar,
.food-list::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}

.recipe-card {
  flex: 0 0 auto;
  width: 140px;
  margin-right: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.recipe-card-content {
  padding: 8px;
}

.recipe-card-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.recipe-card-desc {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 食材卡片区域 */
.food-card {
  flex: 0 0 auto;
  width: 100px;
  margin-right: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.food-card-title {
  font-size: 12px;
  padding: 5px 0;
}

/* 优化卡片布局 */
.section-title {
  margin: 24px 0 16px;
  padding: 0 16px;
  font-size: 18px;
}

.recipe-card,
.food-card {
  transition: transform 0.2s, box-shadow 0.2s;
}

.recipe-card:hover,
.food-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 优化食谱卡片 */
.recipe-card {
  width: 160px;
  margin-right: 12px;
}

.recipe-card-title {
  font-size: 15px;
}

.recipe-card-desc {
  font-size: 13px;
}

/* 优化食品卡片 */
.food-card {
  width: 110px;
  margin-right: 12px;
}

.food-card-title {
  font-size: 13px;
  padding: 8px 0;
}

/* 自定义图片样式 */
.recipe-image-container {
  position: relative;
  width: 100%;
  height: 90px;
  overflow: hidden;
}

.recipe-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  z-index: 1;
}

.hidden {
  visibility: hidden;
}
</style>
